package com.star.common.notify.service;

import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.star.common.notify.config.DingTaskProperties;
import com.star.common.notify.enums.BtnOrientationEnum;
import com.star.common.notify.enums.HideAvatarEnum;
import com.star.common.notify.enums.MessageTypeEnum;
import com.star.common.notify.factory.DingTaskFactory;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * dingTask service类
 *
 * @author zhouhengzhe #公众号：小白的Java进阶之路
 * @version 1.0
 * @date 2023/6/16 14:53
 */
@Slf4j
public class StarDingTaskService {
    private final DingTaskProperties dingTaskProperties;

    private final DingTaskFactory dingTaskFactory;

    public StarDingTaskService(DingTaskProperties dingTaskProperties) {
        this.dingTaskProperties=dingTaskProperties;
        this.dingTaskFactory=new DingTaskFactory();
    }

    private DingTalkClient getClient() {
        return dingTaskFactory.dingTalkClient(dingTaskProperties);
    }

    /**
     * 发送普通文本消息
     *
     * @param content    文本消息
     * @param mobileList 指定@ 联系人
     * @param isAtAll    是否@ 全部联系人
     * @return com.dingtalk.api.response.OapiRobotSendResponse
     */
    public OapiRobotSendResponse sendMessageByText(String content, List<String> mobileList, boolean isAtAll) {
        if (StringUtils.isEmpty(content)) {
            log.warn("content is null");
            return null;
        }

        //参数	参数类型	必须	说明
        //msgtype	String	是	消息类型，此时固定为：text
        //content	String	是	消息内容
        //atMobiles	Array	否	被@人的手机号(在content里添加@人的手机号)
        //isAtAll	bool	否	@所有人时：true，否则为：false
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(content);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        if (!CollectionUtils.isEmpty(mobileList)) {
            // 发送消息并@ 以下手机号联系人
            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
            at.setAtMobiles(mobileList);
            at.setIsAtAll(isAtAll);
            request.setAt(at);
        }
        request.setMsgtype(MessageTypeEnum.TEXT.getMessage());
        request.setText(text);

        OapiRobotSendResponse response = new OapiRobotSendResponse();
        try {
            response = getClient().execute(request);
        } catch (ApiException e) {
            log.error("[send plain text messages]: send message is fail, exception catch {}", e.getMessage());
        }
        return response;
    }

    /**
     * 发送link 类型消息
     *
     * @param title      消息标题
     * @param text       消息内容
     * @param messageUrl 点击消息后跳转的url
     * @param picUrl     插入图片的url
     * @return com.dingtalk.api.response.OapiRobotSendResponse
     */
    public OapiRobotSendResponse sendMessageByLink(String title, String text, String messageUrl, String picUrl) {
        if (StringUtils.isBlank(title) || StringUtils.isBlank(text) || StringUtils.isBlank(messageUrl)) {
            return null;
        }
        //参数	参数类型	必须	说明
        //msgtype	String	是	消息类型，此时固定为：link
        //title	String	是	消息标题
        //text	String	是	消息内容。如果太长只会部分展示
        //messageUrl	String	是	点击消息跳转的URL
        //picUrl	String	否	图片URL
        OapiRobotSendRequest.Link link = new OapiRobotSendRequest.Link();
        link.setTitle(title);
        link.setText(text);
        link.setMessageUrl(messageUrl);
        link.setPicUrl(picUrl);

        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype(MessageTypeEnum.LINK.getMessage());
        request.setLink(link);

        OapiRobotSendResponse response = new OapiRobotSendResponse();
        try {
            response = getClient().execute(request);
        } catch (ApiException e) {
            log.error("[send link type message]: send message fail, exception catch{}", e.getMessage());
        }
        return response;
    }


    /**
     * 发送Markdown 编辑格式的消息
     *
     * @param title        标题
     * @param markdownText 支持markdown 编辑格式的文本信息
     * @param mobileList   消息@ 联系人
     * @param isAtAll      是否@ 全部
     * @return com.dingtalk.api.response.OapiRobotSendResponse
     */
    public OapiRobotSendResponse sendMessageByMarkdown(String title, String markdownText, List<String> mobileList, boolean isAtAll) {
        if (StringUtils.isEmpty(title) || StringUtils.isEmpty(markdownText)) {
            return null;
        }
        //参数	类型	必选	说明
        //msgtype	String	是	此消息类型为固定markdown
        //title	String	是	首屏会话透出的展示内容
        //text	String	是	markdown格式的消息
        //atMobiles	Array	否	被@人的手机号(在text内容里要有@手机号)
        //isAtAll	bool	否	@所有人时：true，否则为：false
        OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
        markdown.setTitle(title);
        markdown.setText(markdownText);

        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype(MessageTypeEnum.MARKDOWN.getMessage());
        request.setMarkdown(markdown);
        if (!CollectionUtils.isEmpty(mobileList)) {
            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
            at.setIsAtAll(isAtAll);
            at.setAtMobiles(mobileList);
            request.setAt(at);
        }

        OapiRobotSendResponse response = new OapiRobotSendResponse();
        try {
            response = getClient().execute(request);
        } catch (ApiException e) {
            log.error("[send markdown type message]: send message fail, exception catch{}", e.getMessage());
        }
        return response;
    }

    /**
     * 整体跳转ActionCard类型的消息发送
     *
     * @param title          消息标题, 会话消息会展示标题
     * @param markdownText   markdown格式的消息
     * @param singleTitle    单个按钮的标题
     * @param singleURL      单个按钮的跳转链接
     * @param btnOrientation 是否横向排列(true 横向排列, false 纵向排列)
     * @param hideAvatar     是否隐藏发消息者头像(true 隐藏头像, false 不隐藏)
     * @return com.dingtalk.api.response.OapiRobotSendResponse
     */
    public OapiRobotSendResponse sendMessageByActionCardSingle(String title, String markdownText, String singleTitle, String singleURL, boolean btnOrientation, boolean hideAvatar) {
        if (StringUtils.isEmpty(title) || StringUtils.isEmpty(markdownText)) {
            return null;
        }
        //参数	类型	必选	说明
        //    msgtype	string	true	此消息类型为固定actionCard
        //    title	string	true	首屏会话透出的展示内容
        //    text	string	true	markdown格式的消息
        //    singleTitle	string	true	单个按钮的方案。(设置此项和singleURL后btns无效)
        //    singleURL	string	true	点击singleTitle按钮触发的URL
        //    btnOrientation	string	false	0-按钮竖直排列，1-按钮横向排列
        //    hideAvatar	string	false	0-正常发消息者头像，1-隐藏发消息者头像
        OapiRobotSendRequest.Actioncard actionCard = new OapiRobotSendRequest.Actioncard();
        actionCard.setTitle(title);
        actionCard.setText(markdownText);
        actionCard.setSingleTitle(singleTitle);
        actionCard.setSingleURL(singleURL);
        // 此处默认为0
        actionCard.setBtnOrientation(btnOrientation ? BtnOrientationEnum.BTN_HORIZONTAL_ARRANGEMENT.getCode()
                : BtnOrientationEnum.BTN_ARRANGED_VERTICALLY.getCode());
        // 此处默认为0
        actionCard.setHideAvatar(hideAvatar ? HideAvatarEnum.HIDDEN_AVATAR.getCode()
                : HideAvatarEnum.SHOW_AVATAR.getCode());

        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype(MessageTypeEnum.ACTION_CARD.getMessage());
        request.setActionCard(actionCard);
        OapiRobotSendResponse response = new OapiRobotSendResponse();
        try {
            response = getClient().execute(request);
        } catch (ApiException e) {
            log.error("[send ActionCard type message]: Overall jump ActionCard type send message failed, exception caught {}", e.getMessage());
        }
        return response;
    }

    /**
     * 独立跳转ActionCard类型 消息发送
     *
     * @param title          标题
     * @param markdownText   文本
     * @param btns           按钮列表
     * @param btnOrientation 是否横向排列(true 横向排列, false 纵向排列)
     * @param hideAvatar     是否隐藏发消息者头像(true 隐藏头像, false 不隐藏)
     * @return com.dingtalk.api.response.OapiRobotSendResponse
     */


    public OapiRobotSendResponse sendMessageByActionCardMulti(String title, String markdownText, List<OapiRobotSendRequest.Btns> btns, boolean btnOrientation, boolean hideAvatar) {
        if (StringUtils.isEmpty(title) || StringUtils.isEmpty(markdownText) || CollectionUtils.isEmpty(btns)) {
            return null;
        }
        //参数	类型	必选	说明
        //msgtype	string	true	此消息类型为固定actionCard
        //title	string	true	首屏会话透出的展示内容
        //text	string	true	markdown格式的消息
        //btns	array	true	按钮的信息：title-按钮方案，actionURL-点击按钮触发的URL
        //btnOrientation	string	false	0-按钮竖直排列，1-按钮横向排列
        //hideAvatar	string	false	0-正常发消息者头像，1-隐藏发消息者头像
        OapiRobotSendRequest.Actioncard actionCard = new OapiRobotSendRequest.Actioncard();
        actionCard.setTitle(title);
        actionCard.setText(markdownText);
        // 此处默认为0
        actionCard.setBtnOrientation(btnOrientation ? BtnOrientationEnum.BTN_HORIZONTAL_ARRANGEMENT.getCode()
                : BtnOrientationEnum.BTN_ARRANGED_VERTICALLY.getCode());
        // 此处默认为0
        actionCard.setHideAvatar(hideAvatar ? HideAvatarEnum.HIDDEN_AVATAR.getCode()
                : HideAvatarEnum.SHOW_AVATAR.getCode());

        actionCard.setBtns(btns);

        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype(MessageTypeEnum.ACTION_CARD.getMessage());
        request.setActionCard(actionCard);
        OapiRobotSendResponse response = new OapiRobotSendResponse();
        try {
            response = getClient().execute(request);
        } catch (ApiException e) {
            log.error("[send ActionCard type message]: Independent jump ActionCard type to send a message failed, exception caught{}", e.getMessage());
        }
        return response;
    }

    /**
     * 发送FeedCard类型消息
     *
     * @param links 链接
     * @return com.dingtalk.api.response.OapiRobotSendResponse
     */
    public OapiRobotSendResponse sendMessageByFeedCard(List<OapiRobotSendRequest.Links> links) {
        if (CollectionUtils.isEmpty(links)) {
            log.warn("kinks is null");
            return null;
        }

        //msgtype	string	true	此消息类型为固定feedCard
        //title	string	true	单条信息文本
        //messageURL	string	true	点击单条信息到跳转链接
        //picURL	string	true	单条信息后面图片的URL
        OapiRobotSendRequest.Feedcard feedcard = new OapiRobotSendRequest.Feedcard();
        feedcard.setLinks(links);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype(MessageTypeEnum.FEED_CARD.getMessage());
        request.setFeedCard(feedcard);
        OapiRobotSendResponse response = new OapiRobotSendResponse();
        try {
            response = getClient().execute(request);
        } catch (ApiException e) {
            log.error("[Send a FeedCard message]: Sending the FeedCard message failed with an exception of {}", e.getMessage());
        }
        return response;
    }

}
